<template>
  <div class="wrapper-add-edit">
    <el-form ref="refForm" :rules="rules" :model="formData" label-width="120px">
      <el-form-item label="所属类别">
        <el-radio-group v-model="tagId" @change="onTagChange">
          <el-radio v-for="item in allCategoryTagList" :key="item.id" :value="item.id" :label="item.label" />
        </el-radio-group>
      </el-form-item>

      <el-form-item label="选择上级分类">
        <el-tree-select
          v-model="formData.idParent"
          :data="treeSelectData"
          :props="{ value: 'id', label: 'label' }"
          :render-after-expand="false"
          :current-node-key="0"
          :default-expanded-keys="selectedKeys"
          value-key="id"
          placeholder="选择上级分类"
          check-strictly
        />
      </el-form-item>

      <el-form-item label="分类名称" prop="label">
        <el-col :span="10">
          <el-input ref="refTitle" v-model="formData.label" maxlength="16" show-word-limit />
        </el-col>
      </el-form-item>

      <el-form-item label="排序值">
        <el-input-number v-model="formData.weight" :min="1" :max="99" controls-position="right" />
      </el-form-item>

      <el-form-item label="标题图">
        <TheUploaderImage :selectedFile="coverImg" @setUploadResult="getUploadResult($event)" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onUpdate">确定修改</el-button>
        <el-button @click="onBack2List">取消并返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { AryToTree } from '@/utils/array'
import { toastSuccess, toastError } from '@/utils/toast'
import { getLStorage, getLStorageObj, getSStorageObj } from '@/utils/web-storage'

import TheUploaderImage from '@/components/UploadImage2Local'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'CategoryEditView',
  components: {
    TheUploaderImage,
  },
  setup() {
    const allCategoryTagList = ref([])
    const tagId = ref(1)
    const tagLabel = ref('')
    const allCategoryList = ref([])
    const treeSelectData = ref([])
    const selectedKeys = ref([])
    const formData = ref({})
    const coverImg = ref([])
    const refForm = ref(null)

    const rules = ref({
      label: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    })
    const initAllCategoryTagList = () => {
      allCategoryTagList.value = JSON.parse(getLStorage('AllCategoryTag'))
      tagId.value = allCategoryTagList.value[0].id
      tagLabel.value = allCategoryTagList.value[0].label
    }
    const onTagChange = (e) => {
      listAllCategory(e)
      for (let i = 0; i < allCategoryTagList.value.length; i++) {
        if (e === allCategoryTagList.value[i].id) {
          formData.value.idParent = allCategoryTagList.value[i].id
          tagLabel.value = allCategoryTagList.value[i].label
        }
      }
    }
    const listAllCategory = (e) => {
      allCategoryList.value = getLStorageObj('AllCategory')
      treeSelectData.value = AryToTree(allCategoryList.value, parseInt(e))
    }
    // 设置封面图
    const getUploadResult = (val) => {
      if (val && val !== '') {
        formData.value.urlCoverImg = JSON.stringify(val)
      } else {
        formData.value.urlCoverImg = ''
      }
    }
    // 得到从list放在query里传过来的的详细资料
    const getQuery = () => {
      const category = getSStorageObj('ParamData')
      if (!category) onBack2List()
      formData.value = category
      formData.value.id = category.id
      formData.value.tag = category.tag
      for (let i = 0; i < allCategoryTagList.value.length; i++) {
        if (category.tag === allCategoryTagList.value[i].label) {
          tagId.value = allCategoryTagList.value[i].id
          tagLabel.value = category.tag
        }
      }
      listAllCategory(category.idParent)
      formData.value.idParent = category.idParent
      // 设置下拉菜单点击时的展开状态
      selectedKeys.value.push(category.idParent)
      selectedKeys.value.push(category.id)
      formData.value.depth = category.depth
      formData.value.label = category.label
      formData.value.weight = category.weight
      // 设置标题图
      if (category.urlCoverImg) {
        coverImg.value.push(JSON.parse(category.urlCoverImg))
      } else {
        coverImg.value = []
      }
    }

    const onUpdate = () => {
      formData.value.tag = tagLabel.value
      for (let i = 0; i < allCategoryList.value.length; i++) {
        if (formData.value.idParent === allCategoryList.value[i].id) {
          formData.value.depth = allCategoryList.value[i].depth + 1
          break
        }
      }
      console.log('formData的值是：', formData.value)
      refForm.value.validate((valid) => {
        if (!valid) {
          toastError('表单验证未通过！')
          return false
        }
        store
          .dispatch('sys_category/modifyAll', formData.value)
          .then(() => {
            toastSuccess('修改分类成功！')
            router.push({ path: 'list-all' })
          })
          .catch((error) => {
            toastError('服务器修改分类返回错误！')
            console.log('服务器修改分类返回错误：', error)
          })
      })
    }
    const onBack2List = () => {
      router.push({ path: 'list-all' })
    }

    onMounted(() => {
      initAllCategoryTagList()
      getQuery()
    })

    return {
      allCategoryTagList,
      tagId,
      tagLabel,
      allCategoryList,
      treeSelectData,
      selectedKeys,
      formData,
      coverImg,
      refForm,
      rules,
      onTagChange,
      initAllCategoryTagList,
      listAllCategory,
      getUploadResult,
      getQuery,
      onUpdate,
      onBack2List,
    }
  },
})
</script>

<style lang="scss" scoped></style>
